import { useForm } from "react-hook-form"
import { z } from "zod"
import { zodResolver } from "@hookform/resolvers/zod"
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormMessage,
} from "@/shared/ui/form"
import { Input } from "@/shared/ui/input"
import { HousingType, OwnType } from "@/app/user/interfaces"
import {
  useCreateRequestMutation,
  useUpdateUserMutation,
} from "@/app/user/userApi"
import { useAppSelector } from "@/app/hooks"
import { selectUser } from "@/app/user/userSlice"
import { Tabs, TabsList, TabsTrigger } from "@/shared/ui/tabs"
import { Button } from "@/shared/ui/button"

const FormSchema = z.object({
  fullName: z
    .string({ required_error: "Обязательное поле" })
    .min(4, "Минимальное количество символов - 2"),
  phone: z
    .string({ required_error: "Обязательное поле" })
    .max(14, "Максимальное количество символов - 14"),
  age: z
    .string({ required_error: "Обязательное поле" })
    .min(1, "Минимальный возраст для создания заявки - 14 лет")
    .max(2, "Максимальный возраст для создания заявки - 100 лет"),
  ownType: z.union([z.literal(OwnType.Own), z.literal(OwnType.Rent)]),
  housingType: z.union([
    z.literal(HousingType.House),
    z.literal(HousingType.Flat),
  ]),
  address: z.string().min(10),
})
const ProfileForm = () => {
  const user = useAppSelector(selectUser)
  const [updateUser] = useUpdateUserMutation()
  const form = useForm<z.infer<typeof FormSchema>>({
    resolver: zodResolver(FormSchema),
    defaultValues: {
      fullName: user?.fullName || "",
      phone: user?.phone || "",
      age: user?.age || null,
      ownType: user?.ownType || OwnType.Rent,
      housingType: user?.housingType || HousingType.Flat,
      address: user?.address || "",
    },
    mode: "onBlur",
    reValidateMode: "onBlur",
  })
  const onSubmit = values => {
    console.log(values)
  }
  return (
    <Form {...form}>
      <form
        onSubmit={form.handleSubmit(onSubmit)}
        className="flex-1 flex flex-col justify-between"
      >
        <div className="flex flex-col gap-4">
          <h2 className="scroll-m-20 text-xl font-medium">Личные данные</h2>
          <FormField
            control={form.control}
            name="fullName"
            render={({ field, fieldState }) => (
              <FormItem>
                <FormControl
                  onBlur={() => {
                    if (!fieldState.invalid && field.value !== user?.fullName) {
                      updateUser({ fullName: field.value, id: user?.id })
                    }
                  }}
                >
                  <Input placeholder="Введите ваше имя" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="phone"
            render={({ field, fieldState }) => (
              <FormItem>
                <FormControl
                  onBlur={() => {
                    if (!fieldState.invalid && field.value !== user?.phone) {
                      updateUser({ phone: field.value, id: user?.id })
                    }
                  }}
                >
                  <Input placeholder="Введите номер" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="age"
            render={({ field, fieldState }) => (
              <FormItem>
                <FormControl>
                  <Input
                    placeholder="Введите возраст"
                    {...field}
                    onBlur={() => {
                      if (
                        !fieldState.invalid &&
                        String(field.value) !== String(user?.age)
                      ) {
                        updateUser({ age: field.value, id: user?.id })
                      }
                    }}
                    onChange={e => field.onChange(e.target.value || "0")}
                  />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
          <h2 className="scroll-m-20 text-xl font-medium">Жилье</h2>
          <FormField
            control={form.control}
            name="ownType"
            render={({ field, fieldState }) => {
              return (
                <FormItem>
                  <FormControl>
                    <Tabs
                      {...field}
                      onValueChange={value => {
                        field.onChange(value)
                        if (!fieldState.invalid && value !== user?.ownType) {
                          updateUser({ ownType: value, id: user?.id })
                        }
                      }}
                      className="w-full"
                    >
                      <TabsList>
                        <TabsTrigger value={OwnType.Own}>Свое</TabsTrigger>
                        <TabsTrigger value={OwnType.Rent}>Снимаю</TabsTrigger>
                      </TabsList>
                    </Tabs>
                  </FormControl>
                </FormItem>
              )
            }}
          />{" "}
          <FormField
            control={form.control}
            name="housingType"
            render={({ field, fieldState }) => {
              return (
                <FormItem>
                  <FormControl>
                    <Tabs
                      {...field}
                      onValueChange={value => {
                        field.onChange(value)
                        if (
                          !fieldState.invalid &&
                          value !== user?.housingType
                        ) {
                          updateUser({
                            housingType: value,
                            id: user?.id,
                          })
                        }
                      }}
                      className="w-full"
                    >
                      <TabsList>
                        <TabsTrigger value={HousingType.Flat}>
                          Квартира
                        </TabsTrigger>
                        <TabsTrigger value={HousingType.House}>Дом</TabsTrigger>
                      </TabsList>
                    </Tabs>
                  </FormControl>
                </FormItem>
              )
            }}
          />
          <FormField
            control={form.control}
            name="address"
            render={({ field, fieldState }) => (
              <FormItem>
                <FormControl
                  onBlur={() => {
                    if (!fieldState.invalid && field.value !== user?.address) {
                      updateUser({ address: field.value, id: user?.id })
                    }
                  }}
                >
                  <Input placeholder="Введите ваш адрес" {...field} />
                </FormControl>
                <FormMessage />
              </FormItem>
            )}
          />
        </div>
      </form>
    </Form>
  )
}
export default ProfileForm
